package com.paireach.bw.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.nanchen.compresshelper.CompressHelper;
import com.paireach.bw.R;
import com.paireach.bw.adapter.KaRejectGridViewAdapter;
import com.paireach.bw.application.MyApplication;
import com.paireach.bw.base.BaseActivity;
import com.paireach.bw.bean.ExceptionInfoBean;
import com.paireach.bw.bean.LocationInfo;
import com.paireach.bw.bean.Reason;
import com.paireach.bw.bean.ReturnInfo;
import com.paireach.bw.event.HttpErrorEvent;
import com.paireach.bw.event.HttpSuccessEvent;
import com.paireach.bw.http.NetUrl;
import com.paireach.bw.http.RequestTag;
import com.paireach.bw.http.WayBillRequest;
import com.paireach.bw.utils.GsonUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;

/**
 * 点击预警列表后进入的   详情界面
 */

public class WarnInfoActivity extends BaseActivity {

    private ImageButton iv_back;
    private TextView tv_title;
    private Button btn_commit;
    private GridView gridview;

    private KaRejectGridViewAdapter gridViewAdapter;

    private Spinner spinner;
    private EditText editText;

    private List<String> pathList = new ArrayList<>();
    private MyAdapter adapter;
    private String reasonInfo;
    private List<Reason> reasonList = new ArrayList<>();
    private Reason selectedItem;
    private ExceptionInfoBean exceptionInfo;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_warn_info);
        exceptionInfo = (ExceptionInfoBean) getIntent().getSerializableExtra("ExceptionInfoBean");
        showProgressDialog();
        new WayBillRequest().rejectReason("263");//获取

        findViews();
        initViews();
    }

    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
        dismissProgressDialog();
        if (event.getRequestTag() == RequestTag.REJECT_SIGN) {
            jsonParse(event.getJson());
        } else if (event.getRequestTag() == RequestTag.REJECT_REASON) {
            List<Reason> list = (List<Reason>) GsonUtil.jsonToList(event.getJson(), new TypeToken<List<Reason>>() {
            }.getType());
            reasonList.clear();
            reasonList.addAll(list);
            if (list != null && list.size() > 0) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    private void jsonParse(String json) {
        ReturnInfo info = GsonUtil.jsonToBean(json, ReturnInfo.class);
        showToast(info.getMsg());
        finish();
    }

    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        dismissProgressDialog();
        if (event.getRequestTag() == RequestTag.REJECT_SIGN) {
            showToast(event.getErrorMessage());
            finish();
        } else if (event.getRequestTag() == RequestTag.REJECT_REASON) {
            showToast(event.getErrorMessage());
        }
    }

    private void initViews() {
        tv_title.setText(getResources().getString(R.string.title_exces));
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        adapter = new MyAdapter();
        spinner.setAdapter(adapter);

        gridViewAdapter = new KaRejectGridViewAdapter(this, pathList);
        gridview.setAdapter(gridViewAdapter);


        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectedItem = (Reason) spinner.getSelectedItem();
                reasonInfo = editText.getText().toString();
                if (TextUtils.isEmpty(selectedItem.getName())) {
                    showToast("请选择原因类别");
                    return;
                }
                if (selectedItem.getName().equals("其他")) {
                    if (TextUtils.isEmpty(reasonInfo)) {
                        showToast("请填写具体原因");
                        return;
                    }
                }

                showProgressDialog();
                LocationInfo locationInfo = ((MyApplication) getApplication()).locationInfo;
                commitInfo(locationInfo);
            }
        });
    }


    private void findViews() {
        iv_back = (ImageButton) findViewById(R.id.img_btn_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        btn_commit = (Button) findViewById(R.id.btn_commit);

        spinner = (Spinner) findViewById(R.id.spinner);
        editText = (EditText) findViewById(R.id.editText);
        gridview = (GridView) findViewById(R.id.gridView_photo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 120 && resultCode == RESULT_OK) {
            // 获取返回的图片列表
            if (pathList != null) {
                pathList.clear();//清除之前的图片
            }
            if (data != null) {
                pathList.addAll(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT));
                if (pathList.size() > 0) {
                    gridViewAdapter.notifyDataSetChanged();
                } else {
                    showToast("您没有选择任何图片");
                }
            }
        }
    }

    private void commitInfo(LocationInfo  location) {//鹰眼：TraceLocation location
        Map<String, File> map = new HashMap<>();
        if (pathList.size() > 0) {
            for (int i = 0; i < pathList.size(); i++) {
                File file = new File(pathList.get(i));
                File newFile = CompressHelper.getDefault(context).compressToFile(file);
                map.put(newFile.getName(), newFile);
            }
        }
        OkHttpUtils.post()
                .url(NetUrl.zhuang + "updateAbnormalSign.a")
                .addParams("id", exceptionInfo.getId() + "")
                .addParams("dictCode", selectedItem.getId() + "")
                .addParams("dictName", selectedItem.getName() + "")
                .addParams("driverName", name)
                .addParams("remark", reasonInfo + "")
                .addParams("lng", location.getLongitude() + "")
                .addParams("lat", location.getLatitude() + "")
                .files("file", map)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        showToast("预警信息上传失败");
                        dismissProgressDialog();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        dismissProgressDialog();
                        ReturnInfo info = GsonUtil.jsonToBean(response, ReturnInfo.class);
                        if (info == null) {
                            showToast("解析json错误，请联系服务端和客户端检查json数据");
                        } else {
                            if (info.getStatus() == 1) {
                                //通知让详情页面刷新
                                setResult(102);
                                finish();
                            } else {
                                showToast(info.getMsg());
                            }
                        }
                    }
                });
    }

    public class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return reasonList.size();
        }

        @Override
        public Object getItem(int i) {
            return reasonList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            TextView tv = new TextView(context);
            tv.setTextSize(18);
            tv.setGravity(Gravity.CENTER);
            tv.setHeight(80);
            tv.setText(reasonList.get(i).getName());
            return tv;
        }
    }
}
